package message;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import event.Tank;
import user.source.TankClient;

/**
 * 
 * @author 
 *
 */
public class TankDeadMsg implements Msg {
	int msgType = Msg.TANK_DEAD_MSG;
	TankClient tc;
	int id;
	
	public TankDeadMsg(int id) {
		this.id = id;
	}
	
	public TankDeadMsg(TankClient tc) {
		this.tc = tc;
	}
	
	
	@Override
	public void send(DatagramSocket ds, String ip, int udpPort) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			//将信息类型发送出去
			dos.writeInt(msgType);
			dos.writeInt(id);
		}catch(IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = baos.toByteArray();
		
		try {
			DatagramPacket dp = new DatagramPacket(buffer,buffer.length,new InetSocketAddress(ip,udpPort));
			ds.send(dp);
		} catch(SocketException e){
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void parse(DataInputStream dis) {
		try {
			int id = dis.readInt();
			//如果坦克的id号和自己的一样，那么这个包没有用处，直接跳过
			if(tc.myTank.id == id) {
				return ;
			}

			
			for(int i=0; i<tc.tanks.size(); i++) {
				Tank tank = tc.tanks.get(i);
				if(tank.id == id) {
					tank.setLive(false);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
